<template>
  <div>
    <a-form :form="form">
      <!-- <div class="form-note-container">
                <p class="form-note">注：账号、姓名、工号提交后不可变更</p>
            </div> -->
      <a-row :gutter="0">
        <a-col :key="1" :span="12">
          <a-form-item
            label="登录账号"
            :labelCol="{ lg: { span: 9 }, sm: { span: 8 } }"
            :wrapperCol="{ lg: { span: 13 }, sm: { span: 10 } }"
          >
            <a-input
              AUTOCOMPLETE="off"
              @focus="() => (this.readonly = false)"
              :read-only="readonly"
              v-if="!filledData.username"
              :max-length="20"
              placeholder="登录账号"
              v-decorator="[
                'username',
                {
                  rules: [
                    { required: true, message: '请输入登录账号' },
                    {
                      pattern: /^[0-9a-zA-Z_]+$/,
                      message:
                        '账号由数字、字母、下划线（_）组成，最多20位字符',
                    },
                  ],
                },
              ]"
            />
            <p v-else>{{ filledData.username }}</p>
          </a-form-item>
        </a-col>
        <a-col :key="2" :span="12">
          <a-form-item
            label="姓名"
            :labelCol="{ lg: { span: 8 }, sm: { span: 8 } }"
            :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
          >
            <a-input
              :max-length="32"
              placeholder="姓名"
              v-if="!filledData.name"
              v-decorator="[
                'name',
                { rules: [{ required: true, message: '请输入姓名' }] },
              ]"
            />
            <p v-else>{{ filledData.name }}</p>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="0">
        <a-col :key="3" :span="24">
          <a-form-item
            label="手机号"
            :labelCol="{ lg: { span: 4 }, sm: { span: 4 } }"
            :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
          >
            <a-input
              placeholder="手机号"
              v-if="!filledData.phone"
              v-decorator="[
                'phone',
                {
                  rules: [
                    {
                      required: true,
                      message: '请输入手机号',
                    },
                    {
                      pattern: /^[1][3456789][0-9]{9}$/,
                      message: '手机号码格式不对',
                    },
                  ],
                  validateTrigger: 'blur',
                },
              ]"
            />
            <p v-else>{{ filledData.phone }}</p>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="0">
        <a-col :key="4" :span="12">
          <a-form-item
            label="归属部门"
            :labelCol="{ lg: { span: 8 }, sm: { span: 8 } }"
            :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
          >
         
            <a-tree-select
              v-decorator="[
                'departmentId',
                { rules: [{ required: true, message: '请选择归属部门' }] },
              ]"
              :treeData="deps"
              placeholder="请选择"
              tree-default-expand-all
              :replace-fields="replaceFields"
            ></a-tree-select>
          </a-form-item>
        </a-col>
        <a-col :key="5" :span="12">
          <a-form-item
            label="角色"
            :labelCol="{ lg: { span: 8 }, sm: { span: 8 } }"
            :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
          >
            <a-select
              v-decorator="[
                'roleId',
                { rules: [{ required: true, message: '选择角色' }] },
              ]"
              placeholder="请选择角色"
            >
              <a-select-option
                v-for="v in roles"
                :key="v.id"
                :value="v.id"
                v-if="v.id !== '1'"
              >
                {{ v.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="0" class="address">
        <a-col :key="6" :span="10">
          <a-form-item
            label="常驻区域"
            :labelCol="{ lg: { span: 10 }, sm: { span: 10 } }"
            :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
          >
            <a-select
              v-decorator="[
                'province',
                { rules: [{ required: true, message: '请选择省份' }] },
              ]"
              placeholder="省"
              @change="changeProvince"
            >
              <a-select-option
                v-for="v in drd.province"
                :key="v.id"
                :value="v.id"
              >
                {{ v.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :key="7" :span="7">
          <a-form-item
            label=""
            :labelCol="{ lg: { span: 8 }, sm: { span: 8 } }"
            :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
          >
            <a-select
              v-decorator="[
                'city',
                { rules: [{ required: true, message: '请选择市' }] },
              ]"
              placeholder="市（地区）"
              @change="changeCity"
            >
              <a-select-option v-for="v in drd.city" :key="v.id" :value="v.id">
                {{ v.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :key="8" :span="7">
          <a-form-item
            label=""
            :labelCol="{ lg: { span: 8 }, sm: { span: 8 } }"
            :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
          >
            <a-select
              v-decorator="[
                'area',
                { rules: [{ required: true, message: '请选择区/县' }] },
              ]"
              placeholder="区/县"
            >
              <a-select-option v-for="v in drd.area" :key="v.id" :value="v.id">
                {{ v.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="10">
        <a-col :key="4" :span="12">
          <a-form-item
            label="下单权限"
            :labelCol="{ lg: { span: 8 }, sm: { span: 8 } }"
            :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
          >
            <a-select
              v-decorator="['isOrder', { initialValue: 1 }]"
              @change="changeIsOrder"
            >
              <a-select-option v-for="v in yesOrNo" :key="v.id" :value="v.id">
                {{ v.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :key="5" :span="12">
          <a-form-item
            label="对应调度"
            :labelCol="{ lg: { span: 8 }, sm: { span: 8 } }"
            :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
          >
            <a-select
              :disabled="!isOrder"
              v-decorator="['scheduleId']"
              placeholder="请选择对应调度"
            >
              <a-select-option
                v-for="v in drd.dispatch"
                :key="v.id"
                :value="v.id"
              >
                {{ v.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="0">
        <a-col :key="4" :span="12">
          <a-form-item
            label="是否调度"
            :labelCol="{ lg: { span: 8 }, sm: { span: 8 } }"
            :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
          >
            <a-select v-decorator="['isSchedule', { initialValue: 0 }]">
              <a-select-option v-for="v in yesOrNo" :key="v.id" :value="v.id">
                {{ v.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="10">
        <a-col :key="4" :span="12">
          <a-form-item
            label="是否飞手"
            :labelCol="{ lg: { span: 8 }, sm: { span: 8 } }"
            :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
          >
            <a-select
              v-decorator="[
                'isPilot',
                { initialValue: 1 },
                { rules: [{ required: true, message: '请选择是否飞手' }] },
              ]"
            >
              <a-select-option v-for="v in yesOrNo" :key="v.id" :value="v.id">
                {{ v.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :key="9" :span="12">
          <a-form-item
            label="AOPA执照"
            :labelCol="{ lg: { span: 8 }, sm: { span: 8 } }"
            :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
          >
            <a-input
              AUTOCOMPLETE="off"
              placeholder="AOPA执照为身份证号"
              v-decorator="[
                'aopa',
                {
                  rules: [
                    {
                      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
                      message: 'AOPA执照编号有误',
                    },
                  ],
                  validateTrigger: 'blur',
                },
              ]"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="0">
        <a-col :key="4" :span="24">
          <a-form-item
            label="是否小包公司"
            :labelCol="{ lg: { span: 5 }, sm: { span: 5 } }"
            :wrapperCol="{ lg: { span: 19 }, sm: { span: 19 } }"
          >
            <a-select
              v-decorator="['isCompany', { initialValue: 1 }]"
              @change="changeCompany"
            >
              <a-select-option v-for="v in yesOrNo" :key="v.id" :value="v.id">
                {{ v.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <div></div>
      <a-row :gutter="0">
        <a-col :key="4" :span="24">
          <a-form-item
            :label="isCompany ? '营业执照' : 'AOPA执照'"
            :labelCol="{ lg: { span: 5 }, sm: { span: 5 } }"
            :wrapperCol="{ lg: { span: 19 }, sm: { span: 19 } }"
          >
            <div class="clearfix">
              <a-upload
                list-type="picture-card"
                :file-list="fileList"
                @preview="handlePreview"
                @change="handleChange"
                :remove="handleRemove"
                :before-upload="beforeUpload"
                :loading="uploading"
                v-decorator="[
                  'uploadUrl',
                  {
                    rules: [
                      {
                        required: true,
                        message: isCompany
                          ? '请上传营业执照'
                          : '请上传AOPA执照',
                      },
                    ],
                  },
                ]"
              >
                <div v-if="fileList.length < 2">
                  <a-icon type="plus" />
                  <div class="ant-upload-text"></div>
                </div>
              </a-upload>
              <a-modal
                :visible="previewVisible"
                :footer="null"
                @cancel="handleCancel"
              >
                <img alt="example" style="width: 100%" :src="previewImage" />
              </a-modal>
            </div>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="10">
        <a-col :key="10" :span="12">
          <a-form-item
            label="密码"
            :labelCol="{ lg: { span: 8 }, sm: { span: 8 } }"
            :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
          >
            <a-input
              AUTOCOMPLETE="off"
              @focus="() => (this.readonly = false)"
              :read-only="readonly"
              placeholder="密码"
              type="password"
              v-if="!filledData.password"
              v-decorator="[
                'password',
                {
                  rules: [
                    {
                      required: true,
                      message: '请输入密码',
                    },
                    {
                      pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z!@#$%^&*()]{6,20}$/,
                      message:
                        '密码由6-20位数字、字母、符号 (!@#$%^&*()) 组成，最少包含一个字母、一个数字',
                    },
                  ],
                  validateTrigger: 'blur',
                },
              ]"
            />
            <p v-if="filledData.password">******</p>
          </a-form-item>
        </a-col>
        <a-col :key="11" :span="12">
          <a-form-item
            label="重输密码"
            :labelCol="{ lg: { span: 8 }, sm: { span: 8 } }"
            :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
            v-if="!filledData.confirmPassword"
          >
            <a-input
              AUTOCOMPLETE="off"
              @focus="() => (this.readonly = false)"
              :read-only="readonly"
              type="password"
              placeholder="重输密码"
              v-decorator="[
                'confirmPassword',
                {
                  rules: [
                    {
                      required: true,
                      message: '请重输密码',
                    },
                    {
                      validator: compareToFirstPassword,
                    },
                  ],
                },
              ]"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="0">
        <a-col :key="12" :span="24">
          <a-form-item
            label="备注"
            :labelCol="{ lg: { span: 4 }, sm: { span: 4 } }"
            :wrapperCol="{ lg: { span: 20 }, sm: { span: 20 } }"
          >
            <a-textarea
              placeholder="请输入备注"
              v-decorator="[
                'remark',
                {
                  rules: [
                    {
                      max: 70,
                      message: '字数不超过70',
                    },
                  ],
                },
              ]"
              :max-length="70"
              :rows="4"
            />
          </a-form-item>
        </a-col>
        <a-col :key="13" :span="24">
          <transition name="slide-fade">
            <p class="account-tips" v-if="errorShow">{{ error }}</p>
          </transition>
        </a-col>
      </a-row>
      <!-- <p>已有MMC账号，<a href="#" @click.prevent="toLogin">去使用</a></p> -->
    </a-form>
  </div>
</template>

<script>
import config from "@/api/config";
import { mapActions, mapGetters } from "vuex";

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}


export default {
  props: ["deps", "roles", "id"],
  data() {
    return {
      form: this.$form.createForm(this),
      labelCol: { lg: { span: 7 }, sm: { span: 7 } },
      wrapperCol: { lg: { span: 10 }, sm: { span: 17 } },
      error: "",
      readonly: true,

      center_username: "",
      center_password: "",
      openid: "",
      token: "",
      errorShow: false,
      errMsg: "",
      yesOrNo: [
        { id: 1, name: "是" },
        { id: 0, name: "否" },
      ],
      drd: {
        province: [],
        city: [],
        area: [],
        dispatch: [],
      },
      uploadUrl: "",
      isCompany: true,
      isOrder: true,

      fileList: [],
      previewVisible: false,
      previewImage: "",
      uploading: false,
      replaceFields: {
        title: 'name',
        key: 'id',
        value: 'id'
      },

    };
  },
  computed: {
    ...mapGetters(["filledData"]),
  },
  methods: {
    ...mapActions(["storeAccountInfo"]),
    onSubmit(form) {
      this.form.validateFields(async (err, values) => {
        
        if (!err) {
          const { fileList } = this;
          let fileUrl = [],
            flag = false;
          const formData = new FormData();
          
          fileList.forEach((file) => {
            if (file.url) {
              fileUrl.push(file.url);
            } else {
              flag = true;
              formData.append("uploadFile", file.originFileObj);
            }
          });
          if (flag) {
            this.uploading = true;
            let uploadRes = await this.http("post", config.uploadURL, formData);
            this.uploading = false;
            fileUrl.push(uploadRes.data.filePath);

          }
          values.file = JSON.stringify(fileUrl);
         

          values.token = this.token;
          values.openid = this.openid;
          // values.file = JSON.stringify([this.uploadUrl])
          let res = {};
          if (this.id) {
             console.log(this.filledData)
            values.id = this.id;
            res = await this.http(
              "put",
              "/user/update",
              Object.assign(values, this.filledData)
            );
          } else {
          
            // let { status, data, message } = await this.postData(Object.assign(values, this.filledData))
            res = await this.postData(Object.assign(values, this.filledData));
             
          }
          let { status, data, message } = res;
          if (status === 1) {

            this.$message.success("创建成功", 1);
            this.$emit("hideCreate");
            this.$emit("getList");
            this.form.resetFields();
            this.storeAccountInfo({});
          } else {
            this.$message.error(
              "该账号已被使用，请确认是否已拥有科比特产品账号或重新命名",
              2
            );
            // this.errorShow = true
            // this.error = message
            // setTimeout(() => {
            //     this.errorShow = false
            // }, 3000)
          }
        }else{
          this.$emit("showtost")
        
        }
      });
    },
    async getDstrict(type, pid) {
      let { data } = await this.http("get", "/dstrict/list", { pid });
      this.drd[type] = data || [];
    },
    changeProvince(val) {
      this.drd.area = [];
      this.form.resetFields(["city", "area"]);
      this.getDstrict("city", val);
    },
    changeCity(val) {
      this.form.resetFields(["area"]);
      this.getDstrict("area", val);
    },
    async getDispatch() {
      let { data } = await this.http("get", "/user/schedule");
      this.drd.dispatch = data || [];
    },
    setSchedule() {
      let scheduleId = this.form.getFieldValue("scheduleId"),
        schedule = this.drd.dispatch[0];
      if (!scheduleId) {
        this.form.setFieldsValue({
          scheduleId: schedule.id,
        });
      }
    },
    changeIsOrder(val) {
      this.isOrder = val === 1 ? true : false;
    },
    changeCompany(val) {
      this.isCompany = val === 1 ? true : false;
    },
    async postData(param) {
      let data = await this.http("post", "/user/create", param);
      return data;
    },
    compareToFirstPassword(rule, value, callback) {
      if (value && value !== this.form.getFieldValue("password")) {
        callback("两次输入密码不一致！");
      } else {
        callback();
      }
    },
    async toLogin() {
      await this.$emit("toUseRegistered", true);
      await this.$emit("toRegisteredStep", false);
      // await this.$nextTick(() => {this.$emit('toUseRegistered', true)})
      // await this.$nextTick(() => {this.useRegistered = true})
    },

    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    handleChange({ fileList }) {
      this.fileList = fileList;
    },
    handleRemove(file) {
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;
    },
    beforeUpload(file) {
      console.log(file);
      this.fileList = [...this.fileList, file];
      return false;
    },
  },
  async mounted() {
    await this.getDstrict("province");
    await this.getDispatch();
    if (this.id) {
      let { data } = await this.http("get", `/user/view/${this.id}`);
      console.log(data);
      let formdata = this.form.getFieldsValue();
      Object.keys(formdata).forEach((key) => {
        if (key == "departmentId" || key == "roleId" || key == "scheduleId") {
          if (data[key] === 0) {
            formdata[key] = undefined;
          } else {
            formdata[key] = data[key];
          }
        } else {
          formdata[key] = data[key];
        }
      });
      this.changeCompany(data.isCompany);
      this.changeIsOrder(data.isOrder);
      this.uploadUrl = data.file ? JSON.parse(data.file) : [];
      formdata.uploadUrl = this.uploadUrl;
      let dispacth = this.drd.dispatch[0];
      formdata.scheduleId = dispacth ? dispacth.id : undefined;
      this.form.setFieldsValue(formdata);
      this.getDstrict("city", data.province);
      this.getDstrict("area", data.city);

      this.fileList =
        JSON.parse(data.file).map((item, index) => {
          return {
            uid: index,
            url: item,
          };
        }) || [];
      console.log(this.fileList);
    }

    this.setSchedule();
  },
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
@import "./../../assets/scss/mixin";

@media (min-width: 992px) {
  .address {
    ::v-deep {
      .ant-col-10 {
        .ant-col-lg-16 {
          width: 50%;
        }
      }
      .ant-col-7 {
        .ant-col-lg-16 {
          width: 90%;
        }
      }
    }
  }
  // .ant-col-lg-16 {
  //     display: block;
  //     -webkit-box-sizing: border-box;
  //     box-sizing: border-box;
  //     width: 50%;
  // }
}

.form-note-container {
  @include fj(space-between);
  align-items: baseline;
}

.tips,
.account-tips {
  position: absolute;
  @include sc(14px, #f5222d);
}

.tips {
  margin-left: 70px;
  margin-top: -10px;
}

.account-tips {
  margin-left: 80px;
  margin-top: -22px;
}

.slide-fade-enter-active {
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
}

.slide-fade-leave-active {
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
}

.slide-fade-enter,
.slide-fade-leave-to {
  transform: translateY(-5px);
  opacity: 0;
}

.slide-fade-leave-to {
  transform: translateY(5px);
  opacity: 0;
}
</style>
